//
//  BaseVC.swift
//  Risac
//
//  Created by remy on 2018/3/18.
//

import UIKit

open class BaseVC: UIViewController {
    
    public struct Options {
        /// 背景色
        public var bgColor: UIColor = .clear
        /// 自定义导航栏后退项
        public var leftBackItem: RisacTopBarItem?
        /// 自定义导航栏取消项
        public var leftCancelItem: RisacTopBarItem?
        /// 是否隐藏系统导航栏
        public var hideSystemNavigationBar: Bool = true
        public init() {}
    }
    private var options: Options
    public static var global: Options = Options()
    /// 控制器是否处于顶层
    public private(set) var isViewAppearing: Bool = false
    /// 控制器是否在导航栈中
    public private(set) var hasViewAppeared: Bool = false
    /// 是否开启右滑返回手势
    public var gesturePopEnabled: Bool = true
    /// 自定义导航栏
    public lazy var topBarView: RisacTopBar = RisacTopBar()
    /// 是否显示自定义导航栏
    open var showTopBar: Bool { return true }
    /// 控制器内容frame
    open var bodyViewFrame: CGRect {
        var frame = self.view.bounds
        if showTopBar {
            frame.origin.y = Size.topHeight
            frame.size.height -= Size.topHeight
        }
        if !hidesBottomBarWhenPushed && tabBarController != nil {
            frame.size.height -= Size.bottomHeight
        }
        return frame
    }
    
    public init(closure: ((inout Options) -> Void)? = nil) {
        options = BaseVC.global
        closure?(&options)
        super.init(nibName: nil, bundle: nil)
        hidesBottomBarWhenPushed = true
    }
    
    required public init?(coder: NSCoder) {
        options = BaseVC.global
        super.init(coder: coder)
        hidesBottomBarWhenPushed = true
    }
    
    public func setOptions(closure: (inout Options) -> Void) {
        closure(&options)
    }
    
    open override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        isViewAppearing = true
        hasViewAppeared = true
        navigationController?.setNavigationBarHidden(options.hideSystemNavigationBar, animated: false)
    }
    
    open override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        isViewAppearing = false
    }
    
    open override func loadView() {
        super.loadView()
        view.backgroundColor = options.bgColor
        automaticallyAdjustsScrollViewInsets = false
        if showTopBar {
            view.addSubview(topBarView)
            let num = navigationController?.viewControllers.count ?? 0
            if num > 1 {
                if let leftItem = options.leftBackItem {
                    topBarView.leftItems = [leftItem.action(UITapGestureRecognizer(target: self, action: #selector(BaseVC.backAction)))]
                }
            } else {
                if isModal {
                    if let leftItem = options.leftCancelItem {
                        topBarView.leftItems = [leftItem.action(UITapGestureRecognizer(target: self, action: #selector(BaseVC.cancelAction)))]
                    }
                }
            }
        }
    }
    
    @objc open func backAction() {
        navigationController?.popViewController(animated: true)
    }
    
    @objc open func cancelAction() {
        dismiss(animated: true)
    }
    
    deinit {
        Risac.print("\(self.metaTypeName) has deinit")
    }
}

// 根控制器为 BaseVC 的设置
extension BaseVC {
    
    public func modalNC(_ vc: UIViewController,
                        animated: Bool = true,
                        completion: (() -> Void)? = nil) {
        self.modal(vc, with: NavigationController.self, animated: animated, completion: completion)
    }
    
    public func modalTransparentNC(_ vc: UIViewController,
                                   animated: Bool = true,
                                   completion: (() -> Void)? = nil) {
        self.modalTransparentNC(vc, with: NavigationController.self, animated: animated, completion: completion)
    }
    
    open override var shouldAutorotate: Bool {
        return false
    }
    
    open override var prefersStatusBarHidden: Bool {
        return false
    }
    
    open override var preferredStatusBarStyle: UIStatusBarStyle {
        return .default
    }
    
    open override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
    
    open override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
        return .portrait
    }
}

// 根控制器为 UITabBarController 的设置
extension UITabBarController {
    
    public func modalNC(_ vc: UIViewController,
                        animated: Bool = true,
                        completion: (() -> Void)? = nil) {
        self.modal(vc, with: NavigationController.self, animated: animated, completion: completion)
    }
    
    public func modalTransparentNC(_ vc: UIViewController,
                                   animated: Bool = true,
                                   completion: (() -> Void)? = nil) {
        self.modalTransparentNC(vc, with: NavigationController.self, animated: animated, completion: completion)
    }
    
    open override var shouldAutorotate: Bool {
        return selectedViewController?.shouldAutorotate ?? false
    }
    
    open override var prefersStatusBarHidden: Bool {
        return selectedViewController?.prefersStatusBarHidden ?? false
    }
    
    open override var preferredStatusBarStyle: UIStatusBarStyle {
        return selectedViewController?.preferredStatusBarStyle ?? .default
    }
    
    open override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return selectedViewController?.supportedInterfaceOrientations ?? .portrait
    }
    
    open override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
        return selectedViewController?.preferredInterfaceOrientationForPresentation ?? .portrait
    }
}
